<?php
/**
 * @author renakeji@163.com
 * @date 2020/5/9
 */

use App\Exceptions\getParamException;

function ListToTree($list, $primaryKey='id', $parentKey = 'pid', $childStr = 'children', $root = 0)
{
    $tree = [];
    if (is_array($list)) {
        //创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$primaryKey]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            //判断是否存在parent
            $parantId = $data[$parentKey];
            if ($root == $parantId) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parantId])) {
                    $parent = &$refer[$parantId];
                    $parent[$childStr][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}


function getParams($params, $vali)
{
    $validate = [];
    foreach ($vali as $v){
        $validate[$v] = 'required';
    }
    $result = Validator::make($params, $validate);
    if($result->fails()){
        $msg = $result->errors()->messages()['title'][0];
        throw new getParamException($msg);
    }
    unset($params['_token']);
    return $params;
}
